from communication.asyncServer import AsyncServer
from public.message import send_qq_text_msg, web_verification_msg
from public.config import get_config, data_path
from public.scheduler import scheduler
from public.log import master_server_logger
from public.lib_tool import MeiFile
from masterServer.masterServer import get_master_server
from datetime import datetime, timedelta
import asyncio
import os


@AsyncServer().register('debug')
async def debug(send, recv):
    try:
        while True:
            s = await recv()
            print(f'收到：{s}')
            if s.isdigit():
                await asyncio.sleep(int(s))
            await send(s)
            print(f'发送：{s}')
    except ConnectionError:
        pass


@send_qq_text_msg.on_receive
def send_qq_text(user_id, text):
    ret = get_master_server().send_to('bot', send_qq_text_msg.build(user_id=user_id, text=text))
    return False if ret is ... else ret


@web_verification_msg.on_receive
def web_verification(qq, code):
    ret = get_master_server().send_to('web', web_verification_msg.build(qq=qq, code=code))
    return False if ret is ... else ret


@scheduler.scheduled_job('cron', hour='0', misfire_grace_time=None)
def backup_mysql():
    mysqldump_path = r'"D:\Program Files\xampp\mysql\bin\mysqldump"'
    user = get_config('sql', 'user')
    password = get_config('sql', 'password')
    host = get_config('sql', 'host')
    db_name = get_config('sql', 'database')
    file_name = datetime.now().strftime('%Y%m%d.sql')
    file_path = data_path('sql_backup', file_name)
    cmd = f'{mysqldump_path} -u {user} -p{password} -h {host} {db_name} > {file_path}'
    os.system(cmd)
    if os.path.exists(file_path):
        master_server_logger.info('备份数据库成功')
        yesterday = datetime.now() - timedelta(1)
        last_file_name = yesterday.strftime('%Y%m%d.sql')
        last_file_path = data_path('sql_backup', last_file_name)
        if os.path.exists(last_file_path):
            with open(file_path, 'rb') as f1:
                a1 = f1.readlines()
            with open(last_file_path, 'rb') as f2:
                a2 = f2.readlines()
            if a1[:-2] == a2[:-2]:
                os.remove(last_file_path)
                master_server_logger.info('已删除内容相同的旧备份文件')
    else:
        master_server_logger.error('备份数据库失败')


@AsyncServer().register('backup_sql')
async def sync_backup_sql(send, recv):
    host, port = (await recv()).split(':')
    file_list = os.listdir(data_path('sql_backup'))
    await send({'file_list': file_list})
    mei_file = MeiFile()
    while file_name := await recv():
        await send(file_name)  # 用作进度同步，值不会用到
        master_server_logger.info(f'发送文件 {file_name} 到：{host}:{port}')
        file_path = data_path('sql_backup', file_name)
        ret = await asyncio.to_thread(mei_file.sendFile, file_path.encode(), host.encode(), int(port))
        master_server_logger.info(f'发送文件 {file_name} 结果：{ret}')
    await send('')


@AsyncServer().register('heartbeat')
async def heartbeat(_, recv):
    name = await recv()
    try:
        await recv()  # 只发不收，使对端一直处于接受态
    except ConnectionResetError:
        master_server_logger.warning(f'与心跳监听客户端[{name}]断连')
